<?php

namespace app\api\controller;

use app\api\model\Config;
use app\common\controller\Api;
use Complex\Exception;
use think\Db;
use wxpay\Wx;
use app\api\model\User as UserModel;
use app\api\model\Integral;
/**
 * 小程序授权登录
 */
class Login extends Api
{
    protected $noNeedLogin = [
        '*'
    ];
    protected $noNeedRight = '*';

    /**
     * 微信授权登录
     */
    public function doLogin()
    {
        $code = $this->request->post('code');
        $yqm  = $this->request->post('yqm','');
        if (!$code) $this->success('非法请求', '', 401);
        $yqm = !empty($yqm) ? $yqm : 0; // 判断是否有邀请码

        $Wx = new Wx();
        $result = $Wx->getAuthLogin($code);
        if (!$result['status']) $this->success('授权失败,请从新操作', '', 401);
        $openid = $result['openid'];
        // 判断有有没此用户
        $user = UserModel::where('openid',$openid)->find();
        // if ($yqm)
        // {
        //     // 获取邀请用户信息
           
        // }
         $user_yqm = UserModel::where('id',$yqm)->find();
        //  var_dump($user_yqm);exit;
        $time = time();
        Db::startTrans();
        try {
            if ($user)
            {
                if ($user['status'] != 0)
                {
                    $this->success('目前无法登录,请联系管理员', '', 401);
                }
                $this->auth->direct($user['id']); //获取用户信息直接登录
                $userinfo = $this->auth->getUserinfo();
                if (empty($userinfo['nickname']) || empty($userinfo['avatar']) || empty($userinfo['mobile']))
                {
                    $log = 2;
                }else{
                    $log = 1;
                }
            }else{
                $log = 2;
                $extend = [
                    'yid'       => $yqm,
                    'openid'    => $openid,
                ];
                $userinfo = $this->auth->register($nickname = '', $password = '12345678', $email = '', $mobile = '', $extend);
               
                $data     = $this->auth->getUserinfo();
                if ($userinfo && $yqm)
                {
                    $UserModel = new UserModel();
                    $config = new Config();
                    $integral = $config->Shareintegral(); // 分享注册获得积分

                    $user_ = $UserModel->getUserInfo($user_yqm['id']);
                    // $user_ =$UserModel::where('id',$user_yqm['id'])->find();
                 
                    // var_dump($user_);
                    // var_dump(111);

                    if ($user_['is_vip'] != 0)
                    {
                        if ($user_['data']['rid'] == '')
                        {
                            $user_['data']['rid'] = $data['id'];
                        }else{
                            $user_['data']['rid'] = ','.$data['id'];
                        }
                        $rid = $user_['data']['rid'];
                        // 更新绑定上下级关系
                        $UserModel::where('id',$user_yqm['id'])->update(['rid' => $rid]);
                        $UserModel::where('id',$data['id'])->update(['yid' => $user_yqm['id']]);
                        $user_['is_vip'] = 2;
                        switch ($user_['is_vip'])
                        {
                            case 1:
                                $integral_data = [
                                    ['uid' => $data['id'], 'integral' => $integral, 'type' => 2, 'create_time' => $time, 'is_type' => 1,],
                                    ['uid' => $user_yqm['id'], 'integral' => $integral, 'type' => 2, 'create_time' => $time, 'is_type' => 1,],
                                ];
                                Integral::insertAll($integral_data);
                                // 添加积分
                                $UserModel::where('id',$user_yqm['id'])->setInc('score',$integral);
                                $UserModel::where('id',$data['id'])->setInc('score',$integral);
                                break;
                            case 2 || 3;
                                $money_data = [
                                    'uid' => $data['id'], 'money' => $integral, 'type' => 'share', 'create_time' => $time, 'is_type' => 1
                                ];
                                Db::name('user_money')->insertGetId($money_data);
                                $integral_data = [
                                    'uid' => $data['id'], 'integral' => $integral, 'type' => 2, 'create_time' => $time, 'is_type' => 1
                                ];
                                Integral::insertGetId($integral_data);
                                $UserModel::where('id',$user_yqm['id'])->setInc('money',$integral);
                                $UserModel::where('id',$data['id'])->setInc('score',$integral);
                                break;
                        }
                    }else{
                        $integral_data = [
                            ['uid' => $data['id'], 'integral' => $integral, 'type' => 2, 'create_time' => $time, 'is_type' => 1,],
                            ['uid' => $user_yqm['id'], 'integral' => $integral, 'type' => 2, 'create_time' => $time, 'is_type' => 1,],
                        ];
                        Integral::insertAll($integral_data);
                        // 添加积分
                        $UserModel::where('id',$user_yqm['id'])->setInc('score',$integral);
                        $UserModel::where('id',$data['id'])->setInc('score',$integral);
                    }
                }
            }
            Db::commit();
        }catch(\Exception $e)
        {
            dump($e->getMessage());
            Db::rollback();
        }
        
        if ($userinfo)
        {
            $usermodel = new UserModel();
            $user = $usermodel->getUserInfo($userinfo['id']);
            $data = [
                'userinfo' => $this->auth->getUserinfo(),
                'is_vip'   => $user['is_vip'],
                'log'      => $log
            ];
            $this->success('登录成功', $data, 200);
        }else{
            $this->success('登录失败', '', 401);
        }

    }

    /**
     * 注册
     */
    public function registered()
    {

        $id    = $this->request->post('id');
        $name  = $this->request->post('name','');
        $avatar   = $this->request->post('avatar','');
        $province = $this->request->post('province','');
        $city     = $this->request->post('city','');
        $code             = $this->request->post('code');

        $wx = new Wx();
        $phone = $wx->getPhoneNumber($code);
        if (empty($id)) $this->success('请从新注册','',401);
        if (empty($name)) $this->success('请输入用户昵称','',400);
        if (empty($avatar)) $this->success('请上传头像','',400);

        $user = UserModel::get($id);
        if (empty($user)) $this->success('用户信息不存在','',401);
        $user->username = $name;
        $user->nickname = $name;
        $user->avatar   = $avatar;
        $user->province = $province;
        $user->city     = $city;
        $user->mobile   = $phone;
        $user->save();
        $usermodel = new UserModel();
        $user = $usermodel->getUserInfo($user['id']);
        $log = 2;
        $data = [
            'userinfo' => $this->auth->getUserinfo(),
            'is_vip'   => $user['is_vip'],
            'log'      => $log
        ];

        $this->success('注册成功',$data,200);
    }


}
